<template>
    <div class="advanced">
        <div class="header">
            <div class="action-left">
                <el-button type="primary">返回</el-button>
            </div>
            <div class="action-right">
                <el-button type="primary" @click="downLoadFile">导出</el-button>
                <el-button type="danger" @click="clearShapes">清空</el-button>
                <el-button type="primary" @click="addShapes">添加</el-button>
            </div>
        </div>
        <div class="container">
            <div class="tabs">
                <div class="tab-item" 
                    v-for="(tab, index) in tabs" 
                    :key="index" 
                    :class="{ active: activeTab === tab.name }"
                    @click="switchTab(tab.name)">
                    <i class="iconfont" :class="tab.icon"></i>
                    <span>{{ tab.label }}</span>
                </div>
            </div>
            <div class="components-container">
                <component 
                    :is="activeTab + 'Panel'"
                    @shape-mousedown="handleMousedown"
                    @shape-click="handleClick"
                    @change-background="handleBackgroundChange"
                    @select-image="handleImageSelect"
                />
            </div>
            <div id="canvas"></div>
            <div class="attrs">
                <div class="attrs-content">
                    <div class="attrs-title">属性</div>
                    <div class="attrs-item">
                        <div class="label">标题</div>
                        <div class="input">
                            <el-input v-model="state.shareAttrs.title" @change="changeShareAttrs"></el-input>
                        </div>
                    </div>
                    <div class="attrs-item">
                        <div class="label">宽</div>
                        <div class="input">
                            <el-input-number :controls="false" v-model="state.shareAttrs.width"
                                @change="changeShareAttrs"></el-input-number>
                        </div>
                    </div>
                    <div class="attrs-item">
                        <div class="label">高</div>
                        <div class="input">
                            <el-input-number :controls="false" v-model="state.shareAttrs.height"
                                @change="changeShareAttrs"></el-input-number>
                        </div>
                    </div>
                    <div class="attrs-item">
                        <div class="label">X</div>
                        <div class="input">
                            <el-input-number :controls="false" v-model="currentShape.x"
                                @change="changeShareAttrs"></el-input-number>
                        </div>
                    </div>
                    <div class="attrs-item">
                        <div class="label">Y</div>
                        <div class="input">
                            <el-input-number :controls="false" v-model="state.shareAttrs.y"
                                @change="changeShareAttrs"></el-input-number>
                        </div>
                    </div>
                    <div class="attrs-title">外形</div>
                    <div class="attrs-item">
                        <div class="label">不透明度</div>
                        <div class="input">
                            <el-slider size="small" style="width: 120px;" :min="0" :max="1" :step="0.01"
                                v-model="state.shareAttrs.opacity" @change="changeShareAttrs"></el-slider>
                            <span class="color">100%</span>
                        </div>
                    </div>

                    <div class="attrs-item">
                        <div class="label">填充</div>
                        <div class="input">
                            <el-color-picker v-model="state.shareAttrs.fill"
                                @change="changeShareAttrs"></el-color-picker>
                            <span class="color">#ffffff</span>
                        </div>
                    </div>
                    <div class="attrs-item">
                        <div class="label">边框</div>
                        <div class="input">
                            <el-color-picker v-model="state.shareAttrs.stroke"
                                @change="changeShareAttrs"></el-color-picker>
                            <span class="color">#ffffff</span>
                        </div>
                    </div>
                    <div class="attrs-item">
                        <div class="label">边框宽度</div>
                        <div class="input">
                            <el-slider size="small" style="width: 120px;" v-model="state.shareAttrs.strokeWidth"
                                @change="changeShareAttrs"></el-slider>
                            <span class="color">100%</span>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <div class="contextMenu" v-show="state.contextMenuVis">
            <div v-for="(item, key) in state.menuList" class="contextMenu-item" :key="key"
                :class="item.disabled ? 'disabled' : 'default'" @click="menuClick(item.type)">
                {{ item.name }}
            </div>
        </div>
    </div>
</template>

<script>
import { KonvaJs } from './utills/konva';
import { componentsShapeType } from './utills/consts'
// import YJimage from './components/bgColor.vue';
import ShapesPanel from './components/Shapes.vue';
import BackgroundPanel from './components/BackgroundPanel.vue';
import ImagePanel from './components/ImagePanel.vue';
import Vue from 'vue';
export default {
    name: 'AdvancedPage',
    components: {
        // YJimage
        ShapesPanel,
        BackgroundPanel,
        ImagePanel
    },
    provide() {
        return {
            // 通过 Vue.observable 保持响应式
            konvaStage: Vue.observable({
                stage: this.state.konva,
                currentTool: 'brush'
            })
        };
    },
    data() {
        return {
            tabs: [
                { name: 'Shapes', label: '图形', icon: 'icon-rect' },
                { name: 'Background', label: '背景', icon: 'icon-bg' },
                { name: 'Image', label: '图片', icon: 'icon-image' }
            ],
            activeTab: 'Shapes',
            state: {
                konva: new KonvaJs('canvas'),
                shareAttrs: {},// 接收图形的属性
                type: '',
                menuList: [
                    { name: '上移动图形', type: "moveUp", disabled: false },
                    { name: '下移动图形', type: "moveDown", disabled: false },
                    { name: '删除', type: "destroy", disabled: false },
                ],
                // 是否展示菜单栏
                contextMenuVis: false,
            },
            textEditing: {
                active: true,
                element: null,
                position: { x: 0, y: 0 }
            },
            currentShape: {
                name: 'Undefined Name', // 名称
                x: 0, // x坐标
                y: 0, // y坐标
                width: 100, // 宽
                height: 100, // 高
                fill: '#000', // 填充颜色
                fontStyle: 'normal'
            },
        }
    },
    mounted() {
        this.init()
        window.addEventListener('keydown', this.handleKeyPress);

        // 禁用默认菜单
        document.oncontextmenu = function () {
            return false;
        }
    },

    beforeDestroy() {
        window.removeEventListener('keydown', this.handleKeyPress);
    },
    methods: {
        switchTab(tabName) {
            this.activeTab = tabName;
        },
        init() {
            this.state.konva.init();
            this.listenerStageEvents();
            this.listenerMaterial();


            // window.onresize = function () {
            //     this.state.konva.onresize();
            // }
        },

        handleKeyPress(e) {
            if (e.key === 'Delete' || e.key === 'Del') {
                this.deleteSelectedNode();
            }
        },

        deleteSelectedNode() {
            const { tr, layer } = this.state.konva;
            const selectedNodes = tr.nodes(); // 获取当前选中的节点
            if (!selectedNodes.length) return
            if (selectedNodes[0].attrs.type === componentsShapeType.BOARD) return
            if (selectedNodes.length > 0) {
                selectedNodes.forEach(node => {
                    node.destroy(); // 销毁节点（自动解除事件绑定）
                });
                tr.nodes([]); // 清空 Transformer 选择
                layer.batchDraw(); // 批量重绘优化性能[4](@ref)
            }
        },

        listenerStageEvents() {
            const { stage } = this.state.konva

            if (!stage) return
            const container = stage.container()

            // 进入页面默认显示画板属性
            this.getSharesAttr(stage.findOne('.board'))

            // 鼠标右键事件
            stage.on('click tap', (e) => {
                const dom = e.target
                const domAttrs = dom.getAttrs()
                if (e.evt.button === 2) {
                    if (domAttrs.type !== componentsShapeType.RECT && domAttrs.type !== componentsShapeType.PARALLELOGRAM && domAttrs.type !== componentsShapeType.RHOMBOUS) {
                        return
                    }
                    this.getSharesAttr(dom)
                    if (dom.getAbsoluteZIndex() === 5) {
                        this.state.menuList[1].disabled = true
                    } else {
                        this.state.menuList[1].disabled = false
                    }
                    this.closeContextMenu()
                    if (!this.state.contextMenuVis) {
                        this.showContextMenu()
                        let menuDom = document.querySelector('.contextMenu')
                        if (!menuDom) return
                        menuDom.style.left = `${e.evt.clientX + 10}px`
                        menuDom.style.top = `${e.evt.clientY + 1}px`
                    }
                }

            })


            // 鼠标双击事件
            stage.on('dblclick dbltap', (e) => {
                // this.state.konva.tr.hide();
                const dom = e.target
                const domAttrs = dom.getAttrs()
                console.log(domAttrs)

                if (domAttrs.type !== componentsShapeType.TEXT) return
                dom.hide()
                this.handleStageDblClick(e)
                this.state.konva.tr.nodes([])
            })

            // 鼠标按压事件
            stage.on('mousedown', (e) => {
                const dom = e.target
                const domAttrs = dom.getAttrs()


                if (e.evt.button === 1) {
                    stage.draggable(true)
                }

                if (e.evt.button === 0) {
                    this.closeContextMenu()
                    if (domAttrs.type === componentsShapeType.CANVAS) {

                        // 点击画板默认显示画板属性
                        this.getSharesAttr(stage.findOne('.board'))
                        this.state.konva.tr.nodes([])
                        return
                    }
                    // 如果不是自己创建的图形，不做任何操作
                    if (!domAttrs.create) return
                    this.getSharesAttr(stage.findOne('.board'))
                    this.getSharesAttr(dom)

                    if (domAttrs.type === componentsShapeType.BOARD) {
                        this.state.konva.tr.nodes([])
                        return
                    }
                    this.state.konva.tr.nodes([dom])
                }

            })

            //鼠标松开事件
            stage.on('mouseup', (e) => {
                if (e.evt.button === 1) stage.draggable(false)
            })



            container.addEventListener('dragover', (e) => {
                e.preventDefault()
            })
            container.addEventListener('drop', (e) => {
                e.preventDefault()
                stage.setPointersPositions(e);
                const shape = this.state.konva.drawShapes(this.state.type, stage.getRelativePointerPosition())
                if (!shape) return
                this.getSharesAttr(shape)

                // 监听图形发生变化
                this.listenerShapeEvents(shape)
            })

            container.addEventListener('keydown', (e) => {
                console.log(e);

            })
        },

        listenerMaterial() {
            const { stage } = this.state.konva
   

            const x = stage.width() / 2 - 200 / 2
            const y = stage.height() / 2 - 100 / 2

            const el = document.querySelectorAll('.shapes-panel-item')
            el.forEach((item) => {
                item.addEventListener('click', (e) => {
                    this.state.konva.tr.nodes([])
                    this.state.konva.drawShapes(this.state.type, { x, y })
                    e.preventDefault()
                })
            })

        },
        // 图形移动属性
        listenerShapeEvents(shape) {
            shape.on('dragmove', (e) => {
                this.getSharesAttr(e.target)
            })

            shape.on('transform', (e) => {
                this.getSharesAttr(e.target)
            })
        },




        handleMousedown(type) {
            this.state.type = type
        },

        // 点击获取当前类型，并且修改
        handleClick(type) {
            this.state.type = type
        },

        // 获取图形属性
        getSharesAttr(share) {
            const { id, title, opacity, fill, stroke, strokeWidth, fontSize, fontFamily, fontStyle, align, shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY, rotation, draggable, visible, width, height, x, y, scaleX, scaleY, points, pointsRotate, pointsRadius, type, radius, color } = share.getAttrs()
            let attrs = { id, title, opacity, fill, stroke, strokeWidth, fontSize, fontFamily, fontStyle, align, shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY, rotation, draggable, visible, width, height, x, y, scaleX, scaleY, points, pointsRotate, pointsRadius, type, radius, color }
            // 如果是棱形
            if (type === componentsShapeType.RHOMBOUS) {
                attrs.width = Math.round(radius * scaleX) * 2
                attrs.height = Math.round(radius * scaleY) * 2
            } else {
                attrs.width = Math.round(width * scaleX)
                attrs.height = Math.round(height * scaleY)
            }
            attrs.x = Math.round(x)
            attrs.y = Math.round(y)
            this.currentShape = attrs
            this.state.shareAttrs = attrs
        },

        // 监听输入值的变化
        changeShareAttrs() {
            const { stage } = this.state.konva
            if (!stage) return
            // 通过查找id找到对应的图形
            const shape = stage.findOne(`#${this.state.shareAttrs.id}`)
            if (!shape) return
            let { id, title, opacity, fill, stroke, strokeWidth, fontSize, fontFamily, fontStyle, align, shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY, rotation, draggable, visible, width, height, x, y, scaleX, scaleY, points, pointsRotate, pointsRadius, type, radius, color } = this.state.shareAttrs
            if (!width && !height && !scaleX && !scaleY) return

            if (type === componentsShapeType.RHOMBOUS) {
                scaleX = width / radius * 0.5
                scaleY = height / radius * 0.5
                shape.setAttrs({ id, title, opacity, fill, stroke, strokeWidth, fontSize, fontFamily, fontStyle, align, shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY, rotation, draggable, visible, width, height, x, y, scaleX, scaleY, points, pointsRotate, pointsRadius, type, radius, color })
            } else {
                width = Math.round(width / scaleX)
                height = Math.round(height / scaleY)
                shape.setAttrs({ id, title, opacity, fill, stroke, strokeWidth, fontSize, fontFamily, fontStyle, align, shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY, rotation, draggable, visible, width, height, x, y, scaleX, scaleY, points, pointsRotate, pointsRadius, type, radius, color })
            }
        },

        // 显示/隐藏菜单栏
        showContextMenu() {
            this.state.contextMenuVis = true
        },

        closeContextMenu() {
            this.state.contextMenuVis = false
        },

        // 点击根据对应类别做对应操作
        menuClick(type) {
            const { shareAttrs, konva } = this.state
            const shape = konva.stage.findOne(`#${shareAttrs.id}`)
            if (!shape) return

            switch (type) {
                case 'moveUp':
                    shape.moveUp()
                    break;
                case 'moveDown':
                    if (shape.getAbsoluteZIndex() === 5) {
                        return
                    }
                    shape.moveDown()
                    break;
                case 'destroy':
                    shape.destroy()
                    break;
            }

            // 点击菜单把变压器清空
            this.state.konva.tr.nodes([])
            this.closeContextMenu()

        },


        // 导出图片
        downLoadFile() {
            const url = this.state.konva.group.toDataURL()
            let link = document.createElement('a')
            link.href = url
            link.download = 'canvas.png'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

        },

        // 清空画板
        clearShapes() {
            let list = this.state.konva.group.find("Shape")
            console.log(list);

            for (let i = 0; i < list.length; i++) {
                const shape = list[i]
                const shapeAttrs = shape.getAttrs()
                if (shapeAttrs.type !== 'board') {
                    shape.destroy()
                }
            }
        },

        //双击事件处理
        handleStageDblClick(e) {
            this.state.konva.tr.nodes([e.target])
            const pos = e.target.absolutePosition();
            this.textEditing = {
                active: true,
                element: e.target,
                position: pos
            };
            this.createTextInput(pos);
        },

        // 创建文本输入框
        createTextInput(position) {
            const input = document.createElement('textarea');
            Object.assign(input.style, {
                position: 'absolute',
                left: `${position.x + 243}px`,
                top: `${position.y + 45}px`,
                width: `${this.textEditing.element.width() + 10}px`,
                height: `${this.textEditing.element.height() + 20}px`,
                fontSize: `${this.state.shareAttrs.fontSize || 18}px`,
                fontFamily: this.state.shareAttrs.fontFamily || 'Arial',
                color: '#000',
                overflow: 'hidden',
                background: 'none',
                outline: 'none',
                zIndex: 9999,
                border: 'none',
                padding: '0px',
                margin: '0px',
                value: this.textEditing.element.text()
            });

            input.value = this.textEditing.element.text();
            document.body.appendChild(input);
            input.focus();

            // 事件监听（网页1的事件处理）
            input.addEventListener('blur', this.finishTextEditing);
        },

        // 完成编辑
        finishTextEditing() {
            this.textEditing.element.show()

            if (!this.textEditing.active) return;

            const input = document.querySelector('textarea');
            this.textEditing.element.text(input.value);
            this.state.konva.layer.batchDraw();

            // 同步属性面板（网页7的右侧面板同步）
            this.$set(this.state.shareAttrs, 'text', input.value);

            document.body.removeChild(input);
            this.textEditing.active = false;
        },

        // 添加画布
        addShapes() {
            this.state.konva.drawBoard()
        },

        handleBackgroundChange(backgroundInfo) {
            // 处理背景颜色变化
            const { stage } = this.state.konva;
            if (!stage) return;
            
            const board = stage.findOne('.board');
            if (board) {
                board.fill(backgroundInfo.color);
                board.opacity(backgroundInfo.opacity);
                this.state.konva.layer.batchDraw();
            }
        },
        
        handleImageSelect(image) {
            // 处理图片选择
            const { stage } = this.state.konva;
            if (!stage) return;
            
            const img = new Image();
            img.onload = () => {
                const imageObj = new window.Konva.Image({
                    x: stage.width() / 2 - 100,
                    y: stage.height() / 2 - 100,
                    image: img,
                    width: 200,
                    height: 200,
                    draggable: true,
                    create: true,
                    id: `image_${Date.now()}`,
                    name: image.name
                });
                
                this.state.konva.layer.add(imageObj);
                this.state.konva.tr.nodes([imageObj]);
                this.state.konva.layer.batchDraw();
                
                // 监听图形发生变化
                this.listenerShapeEvents(imageObj);
                
                // 获取图形属性
                this.getSharesAttr(imageObj);
            };
            
            img.src = image.url;
        },
    }
}
</script>

<style lang="scss" scoped>
@import './scss/index.scss';

.container {
  display: flex;
  
  .tabs {
    background-color: $baseBg;
    width: 60px;
    height: calc(100vh - 51px);
    
    .tab-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 60px;
      color: $baseColor;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        background-color: darken($baseBg, 5%);
      }
      
      &.active {
        background-color: $contentBg;
        border-left: 3px solid #009dff;
      }
      
      i {
        font-size: 24px;
        margin-bottom: 5px;
      }
      
      span {
        font-size: 12px;
      }
    }
  }
  
  .components-container {
    width: 240px;
  }
}
</style>